import os, sys, logging

from threading import Thread
import threading
from PySide2.QtCore import QThread, Signal
from PySide6.QtCore import QModelIndex
from PySide6.QtGui import QStandardItemModel, QStandardItem
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QFileDialog,
    QItemDelegate, QMessageBox
)

from ElasticsearchUtil import getIndexList, LoadElasticsearchIndexListThread
from envUtil import init_env
from gdbutil import getGdbLayer, listGdbLayerPage, PushingData2Es, DriverType
from ui_mainwindow import Ui_mainwindow


class MainWindow(QMainWindow):
    __currentSelectFolderPath = os.path.expanduser('~')
    __gdb_layer_index = 0
    __gdb_layer_name = ''
    __table_view_page = 1
    __table_view_page_size = 20
    __driverType = None

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = Ui_mainwindow()
        self.ui.setupUi(self)
        self.init_widget()
        self.init_test_data()

    def init_widget(self):
        self.ui.pushButton.clicked.connect(self.selectGdbFolderPath)
        self.ui.select_shp_file.clicked.connect(self.selectShpFile)
        self.ui.filePath.setReadOnly(True)
        self.ui.layer_name.activated.connect(self.handleSelectLayerIndex)
        self.ui.load_gdb_data.clicked.connect(self.loadGdbData2TableView)
        self.ui.text_elastic_connect_pushButton.clicked.connect(self.loadElasticsearchIndexList)
        self.ui.pushButton_2.clicked.connect(self.pushingDataByElasticsearch)
        self.ui.es_host.setText('http://192.168.2.186:9200')
        self.ui.filePath.setText('F:\gis数据-本地\DYS_TDLYXZ.gdb')

    def init_test_data(self):
        self.__currentSelectFolderPath = "E:/gis/quanguo.gdb"

    def handleUpdateProgressBar(self, val):
        self.ui.progressBar.setValue(val)

    def pushingDataByElasticsearch(self):
        t = PushingData2Es(self,
                           self.__currentSelectFolderPath,
                           self.__gdb_layer_index,
                           self.ui.es_host.text(),
                           self.ui.es_username.text(),
                           self.ui.es_password.text(),
                           self.ui.es_index.currentData(),
                           self.__driverType
                           )
        t.progress.connect(self.handleUpdateProgressBar)
        t.currentIndex.connect(self.setCurrentSendDataIndex)
        t.start()

    def handleSelectLayerIndex(self, index):
        print(f"选择layerIndex{index}")
        self.__gdb_layer_index = index

    # 加载ES 索引
    def loadElasticsearchIndexList(self):
        esHost = self.ui.es_host.text()
        if esHost is None:
            return
        esPassword = self.ui.es_password.text()
        esUsername = self.ui.es_username.text()
        if esUsername == '':
            esUsername = None
        loadThread = LoadElasticsearchIndexListThread(self, esHost, esUsername, esPassword)
        loadThread.success.connect(self.setESIndexSelectData)
        loadThread.start()

    def setESIndexSelectData(self, data):
        self.ui.es_index.clear()
        for index in data:
            self.ui.es_index.addItem(index, index)

    def setCurrentSendDataIndex(self, v):
        self.ui.currentProgrammaLcdNumber.display(v)

    # 加载Gdb 数据到 TableView 中
    def loadGdbData2TableView(self):
        header, data, count = listGdbLayerPage(
            gdbPath=self.__currentSelectFolderPath, driverType=self.__driverType, layerIndex=self.__gdb_layer_index)
        self.ui.dataCoundLcd.display(count)
        self.setTableViewData(header, data, count)
        pass

    def setTableViewData(self, header=None, data=None, count=0):
        tableModel = QStandardItemModel(len(data), len(header))
        self.ui.tableView.setModel(tableModel)
        delegate = QItemDelegate()
        self.ui.tableView.setItemDelegate(delegate)
        for rowIndex in range(len(data)):
            for colIndex in range(len(header)):
                index = tableModel.index(rowIndex, colIndex, QModelIndex())
                tableModel.setData(index, data[rowIndex][colIndex])
        for cIndex in range(len(header)):
            tableModel.setHorizontalHeaderItem(cIndex, QStandardItem(header[cIndex]))
        self.ui.tableView.setWindowTitle(self.__gdb_layer_name)

    # 选择GDb 文件夹
    def selectGdbFolderPath(self):
        directory = QFileDialog.getExistingDirectory(self, "选择GDB", self.__currentSelectFolderPath)
        if directory:
            print(f'选择的文件夹 {directory}')
            self.ui.filePath.setText(directory)
            self.__currentSelectFolderPath = directory
            self.__driverType = DriverType.OPEN_FILE_GDB_DERIVE
            layers = getGdbLayer(directory, self.__driverType)
            if layers:
                self.ui.layer_name.clear()
                for layer in layers:
                    self.ui.layer_name.addItem(layer['name'], layer)

    def selectShpFile(self):
        fileName = QFileDialog.getOpenFileName(parent=self, caption="选择GDB", dir=self.__currentSelectFolderPath,
                                               filter="*.shp")
        if fileName:
            fileName = fileName[0]
            print(f'选择的文件 {fileName}')
            self.ui.filePath.setText(fileName)
            self.__currentSelectFolderPath = fileName
            self.__driverType = DriverType.ESRI_SHAPEFILE
            layers = getGdbLayer(fileName, self.__driverType)
            if layers:
                self.ui.layer_name.clear()
                for layer in layers:
                    self.ui.layer_name.addItem(layer['name'], layer)


if __name__ == '__main__':
    init_env()
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
